package com.lanyou.esb.redis.proxy.impl;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.base.BaseStrJedisProxy;

/**
 * 成功/失败请求数
 * 
 * @author Davey.wu
 */
@Service
public class ReqResTypeTotalTimesJedisProxy extends BaseStrJedisProxy<Long> {
	public static final String KEYS_SUFFIX = Constants4Redis.PREFIX_REQRESTYPE;

	public ReqResTypeTotalTimesJedisProxy() {
		this.setTimeOut(Constants4Redis.QUANTITY_ANALYSIS_RETENTION_TIME);
	}

	@Override
	public String generateKey(String field) {
		return KEYS_SUFFIX + KEY_SEPARATOR + field;
	}

	@Override
	public String generateKey(String... field) {
		if (field == null) {
			return KEYS_SUFFIX;
		}
		String key = KEYS_SUFFIX;
		for (String str : field) {
			key += KEY_SEPARATOR + str;
		}
		return key;
	}

	@Override
	public String generateKeyFromObject(Long target) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long get(String key) throws JsonParseException,
			JsonMappingException, IOException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(result)) {
			return 0l;
		}
		try {
			return Long.parseLong(result);
		} catch (Exception e) {
			// 类型错误，默认返回0
			return 0l;
		}
	}

	@Override
	public long setex(String key, Long target) throws JsonProcessingException {
		long value = 0;
		if (target != null) {
			value = target.longValue();
		}
		Long result = 0l;
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.incrBy(key, value);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (result == null) {
			return 0l;
		}
		return result;
	}

}
